<template>
  <div class="section clear">
    <h3>自动刷新倒计时，剩余{{ countDown }}秒</h3>
    <Tabs value="table">
      <TabPane label="我的关注" name="table">
        <Table row-key="Code" :columns="columns" :height="autoHeight" :data="shares" size="small" border stripe />
      </TabPane>
    </Tabs>
    <Modal v-model="showEdit" title="编辑" @on-ok="saveShare">
      <Form>
        <form-field label="股票代码" v-model="info.Code" />
        <form-field label="股票名称" v-model="info.Name" />
        <form-field label="收藏日期" type="date" v-model="info.CreatedOn" />
        <form-field label="购买日期" type="date" v-model="info.PurchaseOn" />
        <form-field label="购买价格" v-model="info.PurchasePrice" />
        <form-field label="购买数量" v-model="info.PurchaseQuantity" />
      </Form>
    </Modal>
  </div>
</template>

<script>
import sharePrice from '~/pages/tools/components/SharePrices.vue'

export default {
  components: {
    sharePrice
  },
  data() {
    const $this = this;

    return {
      columns: [
        {
          type: 'expand',
          width: 30,
          render: (h, params) => {
            return h(sharePrice, {
              props: {
                code: params.row.Code
              }
            });
          }
        },
        { title: '名称', key: 'Name', width: 80 },
        { title: '股票代码', key: 'Code', width: 80 },
        {
          title: '关注日期',
          key: 'CreatedOn',
          width: 90,
          render: (h, params) => {
            return h('span', params.row.CreatedOn.split(' ')[0]);
          }
        },
        { title: '关注价格', key: 'BeginPrice', width: 80 },
        {
          title: '关注收益',
          width: 90,
          render: (h, params) => {
            let beginPrice = params.row.BeginPrice;
            let currentPrice = params.row.CurrentPrice;
            let rate = (((currentPrice - beginPrice) / beginPrice) * 100).toFixed(2);

            return h(
              'strong',
              {
                style: {
                  color: currentPrice > beginPrice ? '#ed4014' : '#19be6b'
                }
              },
              rate + '%'
            );
          }
        },
        {
          title: '当前时间',
          key: 'CurrentDate',
          width: 90,
          render: (h, params) => {
            return h('span', params.row.CurrentDate.split(' ')[0]);
          }
        },
        {
          title: '当前价格',
          width: 80,
          render: (h, params) => {
            return h(
              'strong',
              {
                style: {
                  color: params.row.CurrentPrice > params.row.BeginPrice ? '#ed4014' : '#19be6b'
                }
              },
              params.row.CurrentPrice
            );
          }
        },
        {
          title: '当日收益',
          width: 90,
          render: (h, params) => {
            let beginPrice = params.row.YesterdayPrice;
            let currentPrice = params.row.CurrentPrice;
            let rate = (((currentPrice - beginPrice) / beginPrice) * 100).toFixed(2);

            return h(
              'strong',
              {
                style: {
                  color: currentPrice > beginPrice ? '#ed4014' : '#19be6b'
                }
              },
              rate + '%'
            );
          }
        },
        {
          title: '购买日期',
          key: 'PurchaseOn',
          width: 90,
          render: (h, params) => {
            return h('span', (params.row.PurchaseOn || '').split(' ')[0]);
          }
        },
        {
          title: '购买价格',
          key: 'PurchasePrice',
          width: 80
        },
        { title: '购买份额', key: 'PurchaseQuantity' },
        {
          title: '我的收益',
          width: 160,
          fixed: 'right',
          render: (h, params) => {
            if ((params.row.PurchaseQuantity || 0) <= 0) {
              return h('b', 'N/A');
            }

            let beginPrice = params.row.PurchasePrice;
            let currentPrice = params.row.CurrentPrice;
            let rate = (((currentPrice - beginPrice) / beginPrice) * 100).toFixed(2);
            let amount = (params.row.PurchaseQuantity * currentPrice).toFixed(2);

            return h(
              'b',
              {
                style: {
                  color: currentPrice > beginPrice ? '#ed4014' : '#19be6b'
                }
              },
              `${amount} / ${((amount * rate) / 100).toFixed(2)} / ${rate}%`
            );
          }
        },
        {
          title: '操作',
          align: 'center',
          width: 140,
          fixed: 'right',
          render: (h, params) => {
            return h(
              'ButtonGroup',
              {
                props: { shape: 'circle', size: 'small' }
              },
              [
                h(
                  'Button',
                  {
                    props: {
                      type: 'error',
                      icon: 'md-create'
                    },
                    on: {
                      click() {
                        $this.showEdit = true;
                        $this.info = params.row;
                      }
                    }
                  },
                  '编辑'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'primary',
                      icon: 'md-trending-up'
                    },
                    on: {
                      click() {
                        $this.$router.push(`/tools/${params.row.Code}/TrendChart`);
                      }
                    }
                  },
                  '查看'
                )
              ]
            );
          }
        }
      ],
      autoHeight: 300,
      shares: [],
      info: {},
      showEdit: false,
      countDown: 60,
      intervalHandlers: []
    };
  },
  methods: {
    loadShares() {
      this.$http.get('/api/shares/list').then(res => {
        this.shares = res.datas;

        (this.shares || []).forEach(s => {
          s._loading = false;
          s.children = [];
        });
      });
    },
    loadSharePrices(item, callback) {},
    saveShare() {
      this.$http.post('/api/shares/save', this.info).then(res => {
        this.$Message.success('保存成功！');

        this.showEdit = false;
      });
    }
  },
  mounted() {
    this.loadShares();
    this.$bus.on('windowResizeChanged', client => (this.autoHeight = client.height - 65));

    const $this = this;
    this.intervalHandlers.forEach(handler => clearInterval(handler));
    this.intervalHandlers.length = 0;

    let handler1 = setInterval(() => {
      $this.loadShares();
    }, 30 * 1000);

    let handler2 = setInterval(() => {
      $this.countDown--;

      if (!$this.countDown) {
        $this.countDown = 60;
      }
    }, 1000);

    this.intervalHandlers.push(handler1, handler2);
  },
  destroyed() {
    this.intervalHandlers.forEach(handler => clearInterval(handler));
    this.intervalHandlers.length = 0;
  }
};
</script>
<style lang="less" scoped>
h3 {
  text-align: right;
  position: absolute;
  right: 10px;
  top: 10px;
}
.ivu-form-item {
  margin-bottom: 6px;
}
</style>
